<script setup lang="ts">
import { theme, Button, Input, Card, Upload, Typography, message, Spin, List, Popconfirm, Tag } from 'ant-design-vue'
import { UploadOutlined, DatabaseOutlined, FileTextOutlined, DeleteOutlined, PlusOutlined, SearchOutlined } from '@ant-design/icons-vue'
import { computed, ref, onMounted } from 'vue'
import type { UploadProps } from 'ant-design-vue'
import { Codewin } from '@/api/generated/Codewin'
import type { CreateKnowledgeBaseRequest, KnowledgeBaseListVO, RetrieveKnowledgeBaseRequest, RetrieveResult } from '@/api/generated/data-contracts'
import { useAuthStore } from '@/stores/modules/auth'
import { useResourceStore, useUserStore } from '@/stores'

// 获取认证store、资源store和用户store
const authStore = useAuthStore()
const resourceStore = useResourceStore()
const userStore = useUserStore()

// 创建API实例
const api = new Codewin({
  baseURL: import.meta.env.VITE_API_BASE_URL || 'https://www.codewin.top'
})

// 获取认证头的辅助函数
const createAuthHeaders = () => {
  const token = authStore.token
  return token ? { Authorization: `Bearer ${token}` } : {}
}


const { Title, Text, Paragraph } = Typography
const { token } = theme.useToken()

const styles = computed(() => {
  return {
    'layout': {
      'width': '100%',
      'max-width': '1200px',
      'margin': '0 auto',
      'height': 'max(100vh, 1200px)',
      'display': 'flex',
      'background': `${token.value.colorBgContainer}`,
      'font-family': `AlibabaPuHuiTi, ${token.value.fontFamily}, sans-serif`,
    },
    'sidebar': {
      'width': '250px',
      'background': `${token.value.colorBgContainer}`,
      'border-right': `1px solid ${token.value.colorBorder}`,
      'display': 'flex',
      'flex-direction': 'column',
    },
    'mainArea': {
      'flex': 1,
      'display': 'flex',
      'flex-direction': 'column',
      'height': '100%',
    },
    'contentArea': {
      'flex': 1,
      'padding': '0',
      'overflow-y': 'auto',
      'background': `${token.value.colorBgContainer}`,
    },
    'welcomeArea': {
      'display': 'flex',
      'flex-direction': 'column',
      'align-items': 'center',
      'justify-content': 'center',
      'height': '100%',
      'text-align': 'center',
    },
  } as const
})

defineOptions({ name: 'KnowledgeBaseCreation' })

// ==================== State ====================
const currentMode = ref<'detail' | 'create'>('create')
const uploadedFile = ref<File | null>(null)
const knowledgeBaseName = ref('')
const knowledgeBaseDescription = ref('')
const uploadedFileUrl = ref('')
const isProcessingFile = ref(false)
const isSubmitting = ref(false)
const knowledgeBaseList = ref<KnowledgeBaseListVO[]>([])
const isLoadingList = ref(false)
const selectedKnowledgeBase = ref<KnowledgeBaseListVO | null>(null)

// 知识库检索相关状态
const searchQuery = ref('')
const searchResults = ref<RetrieveResult[]>([])
const isSearching = ref(false)
const hasSearched = ref(false)

// ==================== Knowledge Base List ====================
const fetchKnowledgeBaseList = async () => {
  isLoadingList.value = true
  try {
    // 设置Authorization header
    const headers: Record<string, string> = {}
    if (authStore.token) {
      headers['Authorization'] = `Bearer ${authStore.token}`
    }

    let allKnowledgeBases: KnowledgeBaseListVO[] = []

    // 管理员权限校验：管理员只请求普通知识库，避免重复请求
    if (userStore.isAdmin) {
      // 管理员只调用普通知识库接口
      const normalResponse = await api.getKnowledgeBaseList(
        { pageNo: 1, pageSize: 100 },
        { headers }
      )

      // 处理普通知识库数据
      if (normalResponse.data?.code === 0 && normalResponse.data?.data?.list) {
        const normalKbs = normalResponse.data.data.list.map(kb => ({
          ...kb,
          isDefault: 0 // 0表示非默认知识库
        }))
        allKnowledgeBases = [...normalKbs]
      }
    } else {
      // 普通用户同时调用普通知识库和默认知识库接口
      const [normalResponse, defaultResponse] = await Promise.all([
        api.getKnowledgeBaseList(
          { pageNo: 1, pageSize: 100 },
          { headers }
        ),
        api.getDefaultKnowledgeBaseList(
          { pageNo: 1, pageSize: 100 },
          { headers }
        )
      ])

      // 处理普通知识库数据
      if (normalResponse.data?.code === 0 && normalResponse.data?.data?.list) {
        const normalKbs = normalResponse.data.data.list.map(kb => ({
          ...kb,
          isDefault: 0 // 0表示非默认知识库
        }))
        allKnowledgeBases = [...allKnowledgeBases, ...normalKbs]

        // 将普通知识库存储到Pinia
        resourceStore.knowledgeBases = normalResponse.data.data.list
      }

      // 处理默认知识库数据
      if (defaultResponse.data?.code === 0 && defaultResponse.data?.data?.list) {
        const defaultKbs = defaultResponse.data.data.list.map(kb => ({
          ...kb,
          isDefault: 1 // 1表示默认知识库
        }))
        allKnowledgeBases = [...defaultKbs, ...allKnowledgeBases] // 默认知识库放在前面

        // 将默认知识库存储到Pinia
        resourceStore.defaultKnowledgeBases = defaultKbs
      }
    }

    knowledgeBaseList.value = allKnowledgeBases
  } catch (error) {
    console.error('获取知识库列表失败:', error)
    message.error('获取知识库列表失败，请重试')
  } finally {
    isLoadingList.value = false
  }
}

const handleDeleteKnowledgeBase = async (id: string) => {
  try {
    // 设置Authorization header
    const headers: Record<string, string> = {}
    if (authStore.token) {
      headers['Authorization'] = `Bearer ${authStore.token}`
    }

    const response = await api.deleteKnowledgeBase(id, { headers })

    if (response.data?.code === 0) {
      message.success('知识库删除成功！')
      // 重新获取列表
      await fetchKnowledgeBaseList()
      // 如果删除的是当前选中的知识库，清空选中状态
      if (selectedKnowledgeBase.value?.id === id) {
        selectedKnowledgeBase.value = null
      }
    } else {
      throw new Error(response.data?.message || '删除失败')
    }
  } catch (error) {
    console.error('删除知识库失败:', error)
    message.error('知识库删除失败，请重试')
  }
}

const selectKnowledgeBase = (kb: KnowledgeBaseListVO) => {
  selectedKnowledgeBase.value = kb
  currentMode.value = 'detail'
  clearSearch() // 切换知识库时清空搜索状态
}

// ==================== File Upload ====================
const handleFileUpload: UploadProps['customRequest'] = async (options) => {
  const { file, onSuccess, onError } = options
  if (file instanceof File) {
    isProcessingFile.value = true

    try {
      const formData = new FormData()
      formData.append('file', file)

      // 设置Authorization header
      const headers: Record<string, string> = {}
      if (authStore.token) {
        headers['Authorization'] = `Bearer ${authStore.token}`
      }

      const response = await api.uploadFile({ file }, {
        headers
      })

      if (response.data?.code === 0 && response.data?.data) {
        uploadedFile.value = file
        uploadedFileUrl.value = response.data.data
        message.success('文件上传成功！')
        onSuccess?.(response.data.data)
      } else {
        throw new Error('上传失败')
      }
    } catch (error) {
      console.error('文件上传失败:', error)
      message.error('文件上传失败，请重试')
      onError?.(error as Error)
    } finally {
      isProcessingFile.value = false
    }
  }
}

const beforeUpload = (file: File) => {
  const allowedTypes = [
    'text/plain',
    'application/pdf',
    'application/msword',
    'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
  ]
  const allowedExtensions = ['.txt', '.pdf', '.doc', '.docx']

  const isValidType = allowedTypes.includes(file.type) ||
    allowedExtensions.some(ext => file.name.toLowerCase().endsWith(ext))

  if (!isValidType) {
    message.error('只能上传 .txt、.pdf、.doc、.docx 格式的文件！')
    return false
  }
  const isLt1M = file.size / 1024 / 1024 < 1
  if (!isLt1M) {
    message.error('文件大小不能超过 1MB！')
    return false
  }
  return true
}

const removeFile = () => {
  uploadedFile.value = null
  uploadedFileUrl.value = ''
  knowledgeBaseName.value = ''
  knowledgeBaseDescription.value = ''
  message.info('文件已移除')
}

const handleFileSelect = async (event: Event) => {
  const target = event.target as HTMLInputElement
  const file = target.files?.[0]
  if (file) {
    if (!beforeUpload(file)) return

    isProcessingFile.value = true

    try {
      // 设置Authorization header
      const headers: Record<string, string> = {}
      if (authStore.token) {
        headers['Authorization'] = `Bearer ${authStore.token}`
      }

      const response = await api.uploadFile({ file }, {
        headers
      })

      if (response.data?.code === 0 && response.data?.data) {
        uploadedFile.value = file
        uploadedFileUrl.value = response.data.data
        message.success('文件选择成功！')
      } else {
        throw new Error('上传失败')
      }
    } catch (error) {
      console.error('文件上传失败:', error)
      message.error('文件上传失败，请重试')
    } finally {
      isProcessingFile.value = false
    }
  }
}

const handleFileInputClick = () => {
  const fileInput = document.getElementById('file-input') as HTMLInputElement
  if (fileInput) {
    fileInput.click()
  }
}

// ==================== Form Submit ====================
const handleSubmit = async () => {
  if (!knowledgeBaseName.value.trim()) {
    message.warning('请输入知识库名称')
    return
  }

  if (!uploadedFileUrl.value) {
    message.warning('请上传知识库文档')
    return
  }

  isSubmitting.value = true
  try {
    // 准备创建知识库的请求数据
    const createKnowledgeBaseData: CreateKnowledgeBaseRequest = {
      fileUrl: uploadedFileUrl.value,
      name: knowledgeBaseName.value,
      description: knowledgeBaseDescription.value
    }

    // 设置Authorization header
    const headers: Record<string, string> = {}
    if (authStore.token) {
      headers['Authorization'] = `Bearer ${authStore.token}`
    }

    // 调用创建知识库接口
    const response = await api.createKnowledgeBase(createKnowledgeBaseData, {
      headers
    })

    if (response.data?.code === 0) {
      message.success('知识库创建成功！')
      console.log('知识库创建成功，响应数据:', response.data.data)

      // 重新获取知识库列表
      await fetchKnowledgeBaseList()

      // 重置表单
      backToCreate()
    } else {
      throw new Error(response.data?.message || '创建失败')
    }
  } catch (error) {
    console.error('创建知识库失败:', error)
    message.error('知识库创建失败，请重试')
  } finally {
    isSubmitting.value = false
  }
}

// ==================== Navigation ====================
const switchToCreateMode = () => {
  currentMode.value = 'create'
  selectedKnowledgeBase.value = null
  clearSearch() // 清空搜索状态
}

const backToCreate = () => {
  currentMode.value = 'create'
  selectedKnowledgeBase.value = null
  uploadedFile.value = null
  uploadedFileUrl.value = ''
  knowledgeBaseName.value = ''
  knowledgeBaseDescription.value = ''
  clearSearch() // 清空搜索状态
}

// ==================== Knowledge Base Search ====================
const handleSearch = async () => {
  if (!searchQuery.value.trim()) {
    message.warning('请输入搜索内容')
    return
  }

  if (!selectedKnowledgeBase.value?.id) {
    message.warning('请先选择知识库')
    return
  }

  // 检查用户是否已登录
  if (!authStore.token || authStore.isTokenExpired) {
    message.error('请先登录后再进行检索')
    return
  }

  isSearching.value = true
  try {
    const searchRequest: RetrieveKnowledgeBaseRequest = {
      knowledgeBaseId: selectedKnowledgeBase.value.id,
      query: searchQuery.value.trim()
    }

    // 使用API实例调用，传递认证头
    const response = await api.retrieveKnowledgeBase(searchRequest, {
      headers: createAuthHeaders()
    })

    // 检查响应状态和数据
    if (response.data?.code === 0) {
      const results = response.data?.data?.results || []
      searchResults.value = results
      hasSearched.value = true
      
      if (results.length > 0) {
        message.success(`找到 ${results.length} 个相关结果`)
      } else {
        message.info('未找到相关内容，请尝试其他关键词')
      }
    } else {
      // 处理业务错误
      const errorMessage = response.data?.message || '检索失败'
      console.warn('知识库检索业务错误:', response.data)
      message.error(errorMessage)
      searchResults.value = []
      hasSearched.value = true
    }
  } catch (error: any) {
    console.error('知识库检索失败:', error)
    
    // 根据错误类型提供更具体的错误信息
    let errorMessage = '知识库检索失败，请重试'
    
    if (error?.response?.status === 401) {
      errorMessage = '认证失败，请重新登录'
      // 清除过期的token
      authStore.logout()
    } else if (error?.response?.status === 403) {
      errorMessage = '没有权限访问该知识库'
    } else if (error?.response?.status === 404) {
      errorMessage = '知识库不存在或已被删除'
    } else if (error?.response?.status === 400) {
      errorMessage = '请求参数错误，请检查输入内容'
    } else if (error?.response?.status >= 500) {
      errorMessage = '服务器错误，请稍后重试'
    } else if (error?.code === 'NETWORK_ERROR' || error?.message?.includes('Network Error')) {
      errorMessage = '网络连接失败，请检查网络后重试'
    } else if (error?.code === 'TIMEOUT') {
      errorMessage = '请求超时，请重试'
    } else if (error?.message) {
      errorMessage = error.message
    }
    
    message.error(errorMessage)
    searchResults.value = []
    hasSearched.value = true
  } finally {
    isSearching.value = false
  }
}

const clearSearch = () => {
  searchQuery.value = ''
  searchResults.value = []
  hasSearched.value = false
}

// ==================== Lifecycle ====================
onMounted(() => {
  fetchKnowledgeBaseList()
})
</script>

<template>
  <div :style="styles.layout">
    <!-- 左侧知识库列表 -->
    <div :style="styles.sidebar">
      <div class="sidebar-header">
        <Title :level="4" class="sidebar-title">
          知识库
        </Title>
        <Button
          type="primary"
          block
          @click="switchToCreateMode"
          class="create-btn"
        >
          <PlusOutlined />
          新建知识库
        </Button>
      </div>

      <div class="sidebar-content">
        <Spin :spinning="isLoadingList">
          <List
            :data-source="knowledgeBaseList"
            size="small"
            class="knowledge-list"
          >
            <template #renderItem="{ item }">
              <List.Item
                class="knowledge-item"
                :class="{ 'knowledge-item-active': selectedKnowledgeBase?.id === item.id }"
                @click="selectKnowledgeBase(item)"
              >
                <div class="knowledge-item-content">
                  <div class="knowledge-item-header">
                    <div class="knowledge-item-info">
                      <DatabaseOutlined class="knowledge-icon" />
                      <Text strong class="knowledge-name">{{ item.name }}</Text>
                      <Tag v-if="item.isDefault === 1" color="blue" size="small" class="system-tag">系统</Tag>
                    </div>
                    <Popconfirm
                      v-if="item.isDefault !== 1"
                      title="确定要删除这个知识库吗？"
                      ok-text="确定"
                      cancel-text="取消"
                      @confirm="handleDeleteKnowledgeBase(item.id!)"
                      @click.stop
                    >
                      <Button
                        type="text"
                        size="small"
                        danger
                        @click.stop
                        class="delete-btn"
                      >
                        <DeleteOutlined />
                      </Button>
                    </Popconfirm>
                  </div>
                  <Text type="secondary" class="knowledge-desc">
                    {{ item.description || '暂无描述' }}
                  </Text>
                </div>
              </List.Item>
            </template>
          </List>
        </Spin>
      </div>
    </div>

    <!-- 主要内容区域 -->
    <div :style="styles.mainArea">
      <!-- 内容显示区域 -->
      <div :style="styles.contentArea">
        <!-- 知识库详情页面 -->
        <div v-if="currentMode === 'detail' && selectedKnowledgeBase" class="detail-container">
          <div class="detail-content">
            <Card class="detail-card">
              <template #title>
                <div class="detail-header">
                  <DatabaseOutlined class="detail-icon" />
                  <span>知识库详情</span>
                </div>
              </template>
              <div class="detail-info">
                <div class="info-item">
                  <Text strong class="info-label">知识库名称</Text>
                  <Text class="info-value">{{ selectedKnowledgeBase.name }}</Text>
                </div>
                <div class="info-item">
                  <Text strong class="info-label">描述</Text>
                  <Text class="info-value">{{ selectedKnowledgeBase.description || '暂无描述' }}</Text>
                </div>
                <div class="info-item">
                  <Text strong class="info-label">文件信息</Text>
                  <div class="file-info">
                    <FileTextOutlined class="file-icon" />
                    <Text class="file-name">{{ selectedKnowledgeBase.fileName }}</Text>
                    <Text type="secondary" class="file-size">
                      ({{ selectedKnowledgeBase.fileSize ? (selectedKnowledgeBase.fileSize / 1024).toFixed(1) + ' KB' : '未知大小' }})
                    </Text>
                  </div>
                </div>
                <div class="info-item">
                  <Text strong class="info-label">状态</Text>
                  <Text :type="selectedKnowledgeBase.status === 1 ? 'success' : selectedKnowledgeBase.status === 2 ? 'danger' : 'warning'" class="status-text">
                    {{ selectedKnowledgeBase.status === 0 ? '创建中' : selectedKnowledgeBase.status === 1 ? '创建成功' : '创建失败' }}
                  </Text>
                </div>
              </div>
            </Card>

            <!-- 知识库检索模块 -->
            <Card class="search-card">
              <template #title>
                <div class="search-header">
                  <SearchOutlined class="search-icon" />
                  <span>知识库检索</span>
                </div>
              </template>
              
              <!-- 搜索输入区域 -->
              <div class="search-input-section">
                <Input.Search
                  v-model:value="searchQuery"
                  placeholder="请输入要检索的内容..."
                  size="large"
                  :loading="isSearching"
                  @search="handleSearch"
                  @pressEnter="handleSearch"
                  class="search-input"
                >
                  <template #enterButton>
                    <Button type="primary" :loading="isSearching">
                      <SearchOutlined />
                      检索
                    </Button>
                  </template>
                </Input.Search>
              </div>

              <!-- 搜索结果区域 -->
              <div v-if="hasSearched" class="search-results-section">
                <div class="results-header">
                  <Text strong class="results-title">
                    检索结果 ({{ searchResults.length }} 条)
                  </Text>
                  <Button type="link" size="small" @click="clearSearch" class="clear-btn">
                    清空结果
                  </Button>
                </div>

                <div v-if="searchResults.length === 0" class="no-results">
                  <div class="no-results-content">
                    <SearchOutlined class="no-results-icon" />
                    <Text type="secondary">未找到相关内容</Text>
                  </div>
                </div>

                <div v-else class="results-list">
                  <div
                    v-for="(result, index) in searchResults"
                    :key="index"
                    class="result-item"
                  >
                    <div class="result-header">
                      <Text strong class="result-index">结果 {{ index + 1 }}</Text>
                      <Tag color="blue" class="score-tag">
                        相似度: {{ (result.score! * 100).toFixed(1) }}%
                      </Tag>
                    </div>
                    <div class="result-content">
                      <Text class="result-text">{{ result.text }}</Text>
                    </div>
                  </div>
                </div>
              </div>
            </Card>
          </div>
        </div>

        <!-- 创建知识库模式 -->
        <div v-else class="create-container">
          <div class="create-header">
            <Title :level="3" class="create-title">
              <DatabaseOutlined class="create-icon" />
              创建知识库
            </Title>
          </div>

          <div class="create-content">
            <!-- 知识库信息表单 -->
            <div class="form-section">
              <Card class="form-card">
                <template #title>
                  <span class="form-card-title">基本信息</span>
                </template>
                <div class="form-content">
                  <!-- 知识库名称 -->
                  <div class="form-item">
                    <Text strong class="form-label">知识库名称 <Text type="danger">*</Text></Text>
                    <Input
                      v-model:value="knowledgeBaseName"
                      placeholder="请输入知识库名称，如：角色A的背景设定"
                      size="large"
                      class="form-input"
                    />
                  </div>

                  <!-- 知识库描述 -->
                  <div class="form-item">
                    <Text strong class="form-label">知识库描述 <Text type="secondary">(可选)</Text></Text>
                    <Input.TextArea
                      v-model:value="knowledgeBaseDescription"
                      placeholder="请简要描述知识库的内容，如角色的性格特点、背景故事、技能设定等..."
                      :rows="3"
                      show-count
                      :maxlength="500"
                      class="form-textarea"
                    />
                  </div>
                </div>
              </Card>
            </div>

            <!-- 文件上传区域 -->
            <div class="upload-section">
              <Card class="upload-card">
                <template #title>
                  <span class="form-card-title">上传知识库文档</span>
                </template>
                
                <!-- 文件上传区域 -->
                <div v-if="!uploadedFile" class="upload-area">
                  <div class="upload-content">
                    <div class="upload-icon">📚</div>
                    <Title :level="5" class="upload-title">上传知识库文档</Title>
                    <Text type="secondary" class="upload-desc">
                      支持上传 .txt、.pdf、.doc、.docx 格式的文件，文件大小不超过 1MB
                    </Text>

                    <Upload
                      :custom-request="handleFileUpload"
                      :before-upload="beforeUpload"
                      :show-upload-list="false"
                      accept=".txt,.pdf,.doc,.docx"
                      class="upload-component"
                    >
                      <Button type="primary" size="large" :loading="isProcessingFile" class="upload-btn">
                        <UploadOutlined />
                        选择文件上传
                      </Button>
                    </Upload>
                  </div>
                </div>

                <!-- 已上传文件显示 -->
                <div v-else class="uploaded-file">
                  <div class="file-display">
                    <div class="file-info-display">
                      <FileTextOutlined class="file-display-icon" />
                      <div class="file-details">
                        <Text strong class="file-display-name">{{ uploadedFile.name }}</Text>
                        <Text type="secondary" class="file-display-size">
                          ({{ (uploadedFile.size / 1024).toFixed(1) }} KB)
                        </Text>
                      </div>
                    </div>
                    <Button @click="removeFile" class="reselect-btn">重新选择</Button>
                  </div>

                  <!-- 提交按钮 -->
                  <div class="submit-section">
                    <Button
                      type="primary"
                      size="large"
                      :loading="isSubmitting"
                      @click="handleSubmit"
                      class="submit-btn"
                    >
                      创建知识库
                    </Button>
                  </div>
                </div>
              </Card>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
/* 基础样式重置 */
.ant-upload-drag {
  background: #fafafa !important;
}

.ant-upload-drag:hover {
  border-color: #60a5fa !important;
}

.ant-upload-drag.ant-upload-drag-hover {
  border-color: #60a5fa !important;
}

/* 左侧边栏样式 */
.sidebar-header {
  padding: 20px;
  border-bottom: 1px solid #f0f0f0;
  background: transparent;
  color: #333;
}

.sidebar-title {
  color: #333 !important;
  margin: 0 0 16px 0 !important;
  font-weight: 600;
  font-size: 18px;
}

.create-btn {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%) !important;
  border: none !important;
  color: white !important;
  font-weight: 500;
  transition: all 0.3s ease;
}

.create-btn:hover {
  background: linear-gradient(135deg, #5a6fd8 0%, #6a4190 100%) !important;
  border: none !important;
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
}

.sidebar-content {
  flex: 1;
  overflow-y: auto;
  background: #fafbfc;
}

/* 知识库列表样式 */
.knowledge-list {
  padding: 8px;
}

.knowledge-item {
  cursor: pointer;
  border: none !important;
  margin: 4px 0;
  border-radius: 16px;
  background: white;
  transition: all 0.3s ease;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
}

.knowledge-item:hover {
  background: #f8faff !important;
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.1);
}

.knowledge-item-active {
  background: linear-gradient(135deg, #f0f4ff 0%, #e6f0ff 100%) !important;
  border-left: 4px solid #667eea !important;
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.15);
}

.knowledge-item-content {
  width: 100%;
  padding: 12px 16px;
}

.knowledge-item-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 8px;
}

.knowledge-item-info {
  display: flex;
  align-items: center;
  flex: 1;
  min-width: 0;
}

.knowledge-icon {
  color: #667eea;
  margin-right: 8px;
  font-size: 16px;
}

.knowledge-name {
  font-size: 14px;
  color: #1a1a1a;
  margin-right: 8px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  flex: 1;
}

.system-tag {
  margin-left: 8px;
  font-size: 11px;
  padding: 2px 6px;
  border-radius: 4px;
}

.knowledge-desc {
  font-size: 12px;
  color: #666;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  margin: 0;
}

.delete-btn {
  opacity: 0;
  transition: all 0.3s ease;
  color: #ff4d4f !important;
  padding: 4px;
  border-radius: 6px;
}

.knowledge-item:hover .delete-btn {
  opacity: 1;
}

.delete-btn:hover {
  background: rgba(255, 77, 79, 0.1) !important;
}

/* 主内容区域样式 */
.detail-container {
  height: 100%;
  padding: 0;
  padding-top: 48px;
  background: #fafbfc;
}

.detail-content {
  max-width: 800px;
  margin: 0 auto;
}

.detail-card {
  border-radius: 20px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  border: none;
}

.detail-header {
  display: flex;
  align-items: center;
  color: #667eea;
  font-weight: 600;
}

.detail-icon {
  margin-right: 8px;
  font-size: 18px;
}

.detail-info {
  padding: 8px 0;
}

.info-item {
  margin-bottom: 24px;
}

.info-item:last-child {
  margin-bottom: 0;
}

.info-label {
  display: block;
  margin-bottom: 8px;
  color: #333;
  font-size: 14px;
}

.info-value {
  color: #666;
  font-size: 14px;
  line-height: 1.6;
}

.file-info {
  display: flex;
  align-items: center;
}

.file-icon {
  color: #667eea;
  margin-right: 8px;
  font-size: 16px;
}

.file-name {
  margin-right: 8px;
}

.file-size {
  font-size: 12px;
}

.status-text {
  font-weight: 500;
}

/* 创建知识库样式 */
.create-container {
  height: 100%;
  display: flex;
  flex-direction: column;
  background: #fafbfc;
}

.create-header {
  padding: 24px 24px 0;
  margin-bottom: 24px;
}

.create-title {
  color: #667eea !important;
  margin: 0 !important;
  font-weight: 600;
  display: flex;
  align-items: center;
}

.create-icon {
  margin-right: 12px;
  font-size: 24px;
}

.create-content {
  flex: 1;
  padding: 0 24px 24px;
  display: flex;
  flex-direction: column;
  gap: 24px;
}

/* 表单区域样式 */
.form-section {
  flex-shrink: 0;
}

.form-card {
  border-radius: 20px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  border: none;
}

.form-card-title {
  color: #333;
  font-weight: 600;
  font-size: 16px;
}

.form-content {
  padding: 8px 0;
}

.form-item {
  margin-bottom: 20px;
}

.form-item:last-child {
  margin-bottom: 0;
}

.form-label {
  display: block;
  margin-bottom: 8px;
  color: #333;
  font-size: 14px;
}

.form-input {
  border-radius: 8px;
  border: 1px solid #d9d9d9;
  transition: all 0.3s ease;
}

.form-input:hover {
  border-color: #667eea;
}

.form-input:focus {
  border-color: #667eea;
  box-shadow: 0 0 0 2px rgba(102, 126, 234, 0.1);
}

.form-textarea {
  border-radius: 8px;
  border: 1px solid #d9d9d9;
  transition: all 0.3s ease;
}

.form-textarea:hover {
  border-color: #667eea;
}

.form-textarea:focus {
  border-color: #667eea;
  box-shadow: 0 0 0 2px rgba(102, 126, 234, 0.1);
}

/* 上传区域样式 */
.upload-section {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.upload-card {
  border-radius: 20px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  border: none;
  flex: 1;
  display: flex;
  flex-direction: column;
}

.upload-area {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 300px;
}

.upload-content {
  text-align: center;
  max-width: 400px;
  padding: 40px 20px;
}

.upload-icon {
  font-size: 64px;
  margin-bottom: 20px;
  opacity: 0.8;
}

.upload-title {
  color: #333 !important;
  margin: 0 0 16px 0 !important;
  font-weight: 600;
}

.upload-desc {
  display: block;
  margin-bottom: 32px;
  line-height: 1.6;
  color: #666;
}

.upload-component {
  display: inline-block;
}

.upload-btn {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  border-radius: 8px;
  padding: 12px 32px;
  height: auto;
  font-weight: 500;
  transition: all 0.3s ease;
}

.upload-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(102, 126, 234, 0.3);
}

/* 已上传文件样式 */
.uploaded-file {
  padding: 20px 0;
}

.file-display {
  background: #f8faff;
  border: 1px solid #e6f0ff;
  border-radius: 12px;
  padding: 20px;
  margin-bottom: 32px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.file-info-display {
  display: flex;
  align-items: center;
  flex: 1;
}

.file-display-icon {
  font-size: 24px;
  color: #667eea;
  margin-right: 16px;
}

.file-details {
  flex: 1;
}

.file-display-name {
  display: block;
  color: #333;
  font-size: 16px;
  margin-bottom: 4px;
}

.file-display-size {
  font-size: 12px;
  color: #666;
}

.reselect-btn {
  border-radius: 6px;
  border: 1px solid #d9d9d9;
  color: #666;
  transition: all 0.3s ease;
}

.reselect-btn:hover {
  border-color: #667eea;
  color: #667eea;
}

.submit-section {
  text-align: center;
}

.submit-btn {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  border-radius: 8px;
  padding: 12px 48px;
  height: auto;
  font-weight: 600;
  font-size: 16px;
  transition: all 0.3s ease;
}

.submit-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(102, 126, 234, 0.3);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .create-content {
    padding: 0 16px 16px;
    gap: 16px;
  }
  
  .create-header {
    padding: 16px 16px 0;
    margin-bottom: 16px;
  }
  
  .detail-container {
    padding: 16px;
  }
  
  .upload-content {
    padding: 20px 10px;
  }
  
  .upload-icon {
    font-size: 48px;
  }
}

/* 滚动条样式 */
.sidebar-content::-webkit-scrollbar {
  width: 4px;
}

.sidebar-content::-webkit-scrollbar-track {
  background: transparent;
}

.sidebar-content::-webkit-scrollbar-thumb {
  background: rgba(0, 0, 0, 0.1);
  border-radius: 2px;
}

.sidebar-content::-webkit-scrollbar-thumb:hover {
  background: rgba(0, 0, 0, 0.2);
}

/* 右侧内容区域滚动条样式 */
.detail-container::-webkit-scrollbar,
.search-results-section::-webkit-scrollbar,
.results-list::-webkit-scrollbar {
  width: 6px;
}

.detail-container::-webkit-scrollbar-track,
.search-results-section::-webkit-scrollbar-track,
.results-list::-webkit-scrollbar-track {
  background: rgba(0, 0, 0, 0.02);
  border-radius: 3px;
}

.detail-container::-webkit-scrollbar-thumb,
.search-results-section::-webkit-scrollbar-thumb,
.results-list::-webkit-scrollbar-thumb {
  background: linear-gradient(180deg, rgba(102, 126, 234, 0.1) 0%, rgba(102, 126, 234, 0.15) 100%);
  border-radius: 3px;
  transition: all 0.3s ease;
}

.detail-container::-webkit-scrollbar-thumb:hover,
.search-results-section::-webkit-scrollbar-thumb:hover,
.results-list::-webkit-scrollbar-thumb:hover {
  background: linear-gradient(180deg, rgba(102, 126, 234, 0.2) 0%, rgba(102, 126, 234, 0.25) 100%);
}

/* 主内容区域滚动条样式 */
.detail-content::-webkit-scrollbar,
div[style*="overflow-y: auto"]::-webkit-scrollbar {
  width: 6px;
}

.detail-content::-webkit-scrollbar-track,
div[style*="overflow-y: auto"]::-webkit-scrollbar-track {
  background: rgba(0, 0, 0, 0.02);
  border-radius: 3px;
}

.detail-content::-webkit-scrollbar-thumb,
div[style*="overflow-y: auto"]::-webkit-scrollbar-thumb {
  background: linear-gradient(180deg, rgba(102, 126, 234, 0.08) 0%, rgba(102, 126, 234, 0.12) 100%);
  border-radius: 3px;
  transition: all 0.3s ease;
}

.detail-content::-webkit-scrollbar-thumb:hover,
div[style*="overflow-y: auto"]::-webkit-scrollbar-thumb:hover {
  background: linear-gradient(180deg, rgba(102, 126, 234, 0.15) 0%, rgba(102, 126, 234, 0.2) 100%);
}

/* 动画效果 */
@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.detail-card,
.form-card,
.upload-card {
  animation: fadeIn 0.3s ease-out;
}

/* Ant Design 组件样式覆盖 */
:deep(.ant-card-head) {
  border-bottom: 1px solid #f0f0f0;
  padding: 16px 24px;
}

:deep(.ant-card-body) {
  padding: 24px;
}

:deep(.ant-list-item) {
  padding: 0 !important;
  border: none !important;
}

:deep(.ant-input:focus),
:deep(.ant-input-focused) {
  border-color: #667eea;
  box-shadow: 0 0 0 2px rgba(102, 126, 234, 0.1);
}

:deep(.ant-btn-primary) {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
}

:deep(.ant-btn-primary:hover) {
  background: linear-gradient(135deg, #5a6fd8 0%, #6a4190 100%);
}

/* 知识库检索模块样式 */
.search-card {
  border-radius: 20px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  border: none;
  margin-top: 24px;
}

.search-header {
  display: flex;
  align-items: center;
  color: #667eea;
  font-weight: 600;
}

.search-icon {
  margin-right: 8px;
  font-size: 18px;
}

.search-input-section {
  margin-bottom: 24px;
}

.search-input {
  width: 100%;
}

:deep(.search-input .ant-input-search-button) {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  border-radius: 0 8px 8px 0;
}

:deep(.search-input .ant-input-search-button:hover) {
  background: linear-gradient(135deg, #5a6fd8 0%, #6a4190 100%);
}

.search-results-section {
  border-top: 1px solid #f0f0f0;
  padding-top: 20px;
}

.results-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 16px;
}

.results-title {
  color: #333;
  font-size: 16px;
}

.clear-btn {
  color: #667eea;
  padding: 0;
}

.clear-btn:hover {
  color: #5a6fd8;
}

.no-results {
  text-align: center;
  padding: 40px 20px;
}

.no-results-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 12px;
}

.no-results-icon {
  font-size: 48px;
  color: #d9d9d9;
}

.results-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.result-item {
  background: #fafbfc;
  border: 1px solid #f0f0f0;
  border-radius: 12px;
  padding: 16px;
  transition: all 0.3s ease;
}

.result-item:hover {
  border-color: #667eea;
  box-shadow: 0 2px 8px rgba(102, 126, 234, 0.1);
}

.result-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 12px;
}

.result-index {
  color: #333;
  font-size: 14px;
}

.score-tag {
  font-size: 12px;
  border-radius: 6px;
}

.result-content {
  line-height: 1.6;
}

.result-text {
  color: #666;
  font-size: 14px;
  word-break: break-word;
}
</style>
